<template>
  <div class="h-[12px]"></div>
  <div class="detail-style" id="scrollContainer" @scroll="handleScroll">
    <div id="top"></div>
    <Flow ref="FlowRef"></Flow>
    <div
      class="flex"
      :class="handleType != 'view' ? 'pb-42' : 'pb-30'"
      ref="scrollContainer"
    >
      <div class="flex-1" style="width: 80%">
        <el-card class="box-card mt-2" shadow="never">
          <div id="spuInfo" class="header-title mb-4 w-28">SPU信息</div>
          <SpuInfo
            ref="spuInfoRef"
            v-model="form"
            @initsku="initsku"
            @sync="syncName"
          ></SpuInfo>
        </el-card>

        <el-card class="box-card mt-2 mb-[10px]" shadow="never">
          <div id="multiattribute" class="header-title mb-4 w-28">多属性设置</div>
          <MultiAttribute
            ref="multiAttributeRef"
            v-model="form"
            :spu="form.spu"
            @change="changeAttribute"
          >
          </MultiAttribute>
        </el-card>
        <div id="SKUOffsetTop"></div>
        <el-affix :offset="95">
          <el-tabs
            v-model="activeName"
            type="card"
            class="px-2 pt-2 bg-[#fff] border-b border-solid border-[#e4e7ed]"
            @tab-click="handleTag"
          >
            <el-tab-pane
              v-for="(item, index) in goods_sku_list"
              :key="index"
              :label="item.sku"
              :name="item.sku"
            >
              <template #label>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="item.sku_cn_title"
                  placement="top-start"
                >
                  {{ item.sku || item.custom_sku }}
                </el-tooltip>
              </template>
            </el-tab-pane>
          </el-tabs>
        </el-affix>
        <el-card
          class="box-card card-affix"
          shadow="never"
          v-if="form?.goods_sku?.length"
        >
          <div class="flex justify-between items-center h-[44px]">
            <div id="SKUMaintain" class="font-bold">SKU维护</div>
            <div class="flex">
              <el-button v-if="form.goods_sku.length > 1" @click="copySKUFun('all')"
                >复制SKU信息</el-button
              >
            </div>
          </div>

          <div class="card-affix-tab" v-if="current_sku">
            <!-- <template v-for="(item, index) in form.goods_sku" :key="index">
              <div v-if="activeName == item.sku"> -->
            <el-card class="box-card card-content-line" shadow="never">
              <div id="SKUInfo" class="SKUInfo header-title">产品基础信息</div>
              <SellInfo
                class="line"
                ref="sellInfoRef"
                v-model="current_sku"
                @changeGeneralactive="changeGeneralactive"
              ></SellInfo>
            </el-card>
            <el-card class="box-card mt-2 card-content-line" shadow="never">
              <div id="peopleInfo" class="header-title peopleInfo">处理人员信息</div>
              <PeopleInfo ref="peopleInfoRef" v-model="current_sku"></PeopleInfo>
            </el-card>
            <el-card class="box-card mt-2 card-content-line" shadow="never">
              <div
                id="weightSizeInfo"
                class="flex justify-between items-center weightSizeInfo"
              >
                <div class="header-title">产品重量尺寸</div>
                <div>
                  <el-button
                    v-if="handleType != 'view' && form.goods_sku.length > 1"
                    @click="copySKUFun('weightSizeInfo')"
                    >复制重量尺寸信息</el-button
                  >
                </div>
              </div>
              <weightSizeInfo
                ref="weightSizeInfoRef"
                v-model="current_sku"
                class="line"
              ></weightSizeInfo>
            </el-card>

            <div id="pictureId" class="pictureId"></div>

            <el-card class="box-card mt-2 card-content-noline border-card" shadow="never">
              <!-- 产品图片设置 -->
              <div id="pictureId" class="pictureId">
                <Picture
                  ref="pictureRefs"
                  v-model="current_sku.goods_sku_gallery"
                  :currentIndex="current_index"
                ></Picture>
              </div>
            </el-card>

            <el-card
              class="box-card mt-2 flex w-full tabs-style card-content-noline border-card"
              shadow="never"
            >
              <Remark v-model="current_sku.goods_sku_remark" id="SKURemark">
                <template #header>
                  <div class="flex justify-between">
                    <div class="header-title mt-[8px]">备注信息</div>
                  </div>
                </template>
              </Remark>
            </el-card>

            <el-card
              class="box-card mt-2 w-full tabs-content-border certificate-card"
              shadow="never"
            >
              <Certificate
                ref="CertificateRef"
                v-model="current_sku.goods_sku_certificate"
              >
                <template #header>
                  <div id="certificateFile" class="header-title mb-2">证书/文件</div>
                </template>
              </Certificate>
            </el-card>

            <el-card class="box-card mt-2 w-full tabs-content-border" shadow="never">
              <recommend
                v-model="current_sku.goods_sku_recommended_platform"
                :info="{
                  packing_size_cm: current_sku.packing_size_cm,
                  package_weight: current_sku.gross_weight_g,
                }"
              >
                <template #header>
                  <div id="platformSite" class="header-title platformSite">
                    推荐平台/站点
                  </div>
                </template>
              </recommend>
            </el-card>

            <el-card
              class="box-card mt-2 w-full tabs-style tabs-content-border"
              shadow="never"
            >
              <el-tabs
                v-model="generalactive"
                type="card"
                class="header-mb0"
                @tab-change="changeTab"
                id="GeneralInfoRef"
              >
                <el-tab-pane label="供应商信息" name="Supplier" />
                <el-tab-pane label="商品描述" name="2"> </el-tab-pane>
                <el-tab-pane label="组合SKU" name="4" v-if="current_sku.is_combination">
                </el-tab-pane>
                <el-tab-pane label="产品头程运费设置" name="8"> </el-tab-pane>
                <el-tab-pane label="渠道SKU" name="5"> </el-tab-pane>
                <el-tab-pane label="拿样记录" name="6"> </el-tab-pane>
                <el-tab-pane
                  label="关联辅料"
                  name="7"
                  v-if="current_sku.sku_product_type != 2"
                >
                </el-tab-pane>
              </el-tabs>

              <div class="card-body">
                <div
                  id="GeneralInfoRef"
                  class="header-title mb-4 inline-block GeneralInfoRef"
                >
                  SKU综合信息
                </div>

                <!-- 供应商信息 -->
                <div v-if="generalactive == 'Supplier'">
                  <Supplier
                    ref="supplierRef"
                    v-model="current_sku.goods_sku_supplier"
                    :custom_sku="current_sku.custom_sku"
                    :sku="current_sku.sku"
                    :sku_product_type="current_sku.sku_product_type"
                    v-if="generalactive == 'Supplier'"
                    :index="current_index"
                    :info="{
                      custom_sku: current_sku.custom_sku,
                      sku: current_sku.sku,
                      sku_product_type: current_sku.sku_product_type,
                      dev_status: current_sku.dev_status,
                      sku_id: current_sku.id,
                      spu_category: form.spu_category,
                      is_dangerous: form.is_dangerous,
                      brand_name: current_sku.goods_sku_sales_info.brand_name,
                    }"
                    @copySKU="copySKUFun"
                  />
                </div>

                <!-- 商品描述 -->
                <div v-if="generalactive == '2'">
                  <Ddescribe
                    ref="DdescribeRef"
                    v-model="current_sku.goods_sku_description"
                  ></Ddescribe>
                </div>

                <!-- 组合SKU -->
                <div v-if="generalactive == '4'">
                  <GroupSku
                    ref="GroupSkuRef"
                    v-model="current_sku.goods_sku_combination_sku"
                  ></GroupSku>
                </div>

                <!-- 产品头程运费设置 -->
                <div v-if="generalactive == '8'">
                  <HeadFreight
                    ref="headFreightRef"
                    v-model="current_sku.goods_sku_head_freight"
                    :info="{
                      sku: current_sku.sku,
                      gross_weight_g: current_sku.gross_weight_g,
                      packing_size_cm: current_sku.packing_size_cm,
                      goods_sku_supplier: current_sku.goods_sku_supplier,
                      exchange_rate: exchange_rate,
                    }"
                  ></HeadFreight>
                </div>

                <!-- 渠道SKU -->
                <ChannelSku
                  ref="ChannelSkuRef"
                  :custom_sku="current_sku.custom_sku"
                  v-if="generalactive == '5'"
                >
                </ChannelSku>

                <!-- 拿样记录 -->
                <Sample ref="SampleRef" v-if="generalactive == '6'"> </Sample>

                <!-- 关联辅料 -->
                <Ingredient
                  class="border border-t-0 py-2 px-2"
                  ref="IngredientRef"
                  v-model="current_sku.goods_sku_accessories"
                  :custom_sku="current_sku.custom_sku"
                  :sku="current_sku.sku"
                  :supplierInfo="current_sku.goods_sku_supplier"
                  v-if="generalactive == '7'"
                >
                </Ingredient>
              </div>

              <div id="bottom" ref="bottomRef"></div>
            </el-card>
          </div>
        </el-card>
      </div>
      <div class="sidebar">
        <el-affix :offset="affixtab ? 85 : 85">
          <div class="broadside w-52 mr-1.5 px-6">
            <div
              :class="[
                'broadside-item cursor-pointer',
                item.name == scrollPosition.activeModule ? 'active' : '',
              ]"
              v-for="(item, index) in filteredSKUItems"
              :key="index"
              @click="scrollTop(item.name, item.offset)"
            >
              {{ item.label }}
            </div>
          </div>
          <div
            :class="[
              'mt-3 roll',
              scrollPosition.isTopBottom == 'top' ? 'rollActive' : '',
            ]"
            @click="scrollTop('top')"
          >
            <svg-icon
              class="text-[32px] text-[--base-color]"
              icon-class="roll-top"
            ></svg-icon>
          </div>
          <div
            :class="[
              'mt-3 roll',
              scrollPosition.isTopBottom == 'bottom' ? 'rollActive' : '',
            ]"
            @click="scrollTop('bottom')"
          >
            <svg-icon
              class="text-[32px] text-[--base-color]"
              icon-class="roll-down"
            ></svg-icon>
          </div>
        </el-affix>
      </div>
      <div class="handle flex justify-center items-center py-4 fixed bottom-0 z-index">
        <div class="flex justify-start items-center" v-if="handleType != 'view'">
          <el-checkbox v-model="form.is_notify" label="消息通知审核人员" size="large" />
          <select-personnel
            class="ml-2"
            v-model="form.dev_reviewer_id"
            placeholder="请选择"
          ></select-personnel>
        </div>
        <div class="ml-20 mr-20">
          <el-button :type="handleType == 'view' ? 'primary' : ''" @click="back"
            >返回</el-button
          >

          <template v-if="handleType != 'view'">
            <el-button type="primary" plain @click="handleInfringement"
              >检测侵权</el-button
            >
            <el-button type="primary" @click="save">保存并继续编辑</el-button>
            <!-- <el-checkbox
              class="ml-2"
              v-model="form.is_push_to_saihe"
              label="推送赛盒"
              :true-label="1"
              :false-label="0"
              size="large"
            /> -->
            <template v-if="form.dev_status == 2 || form.dev_status == 3">
              <el-button type="primary" @click="handleAudit(true)">审核通过</el-button>
              <el-button type="danger" @click="handleAudit(false)">审核不通过</el-button>
            </template>
          </template>
        </div>
        <div
          class="flex justify-start items-center text-gray-400 mt-2 text-xs"
          v-if="handleType != 'view'"
        >
          <svg-icon icon-class="hint_line" />
          系统自动保留未提交的信息，未保存的信息有效期为24H，请及时保存。
        </div>
      </div>
    </div>
    <!-- 底部操作 -->
    <el-dialog
      v-model="dialogVisible"
      title="提示"
      width="30%"
      align-center
      draggable
      :z-index="2000"
    >
      <div v-html="errorMessage"></div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmNew">获取最新数据</el-button>
          <el-button type="primary" @click="confirmCover">确认覆盖</el-button>
        </span>
      </template>
    </el-dialog>
    <InfringementDetection ref="infringementRef"></InfringementDetection>
    <copySKU ref="copySKURef"></copySKU>
  </div>
</template>

<script name="TaskProductAdd" setup>
import SpuInfo from "../componentsDetail/SpuInfo.vue";
import SellInfo from "../componentsDetail/SellInfo.vue";
import PeopleInfo from "../componentsDetail/PeopleInfo.vue";
import MultiAttribute from "../componentsDetail/Attribute/index.vue";
import Picture from "../componentsDetail/Picture/index.vue";
import Remark from "../componentsDetail/Remark.vue";
import Certificate from "../componentsDetail/Certificate/index.vue";
import Flow from "../componentsDetail/Flow.vue";
import Ddescribe from "../componentsDetail/GeneralInfo/Ddescribe.vue";
import Supplier from "../componentsDetail/Supplier/index";
import GroupSku from "../componentsDetail/GeneralInfo/GroupSku.vue";
import ChannelSku from "../componentsDetail/GeneralInfo/ChannelSku.vue";
import Sample from "../componentsDetail/GeneralInfo/Sample/index";
import Ingredient from "../componentsDetail/GeneralInfo/Ingredient/index";
import recommend from "../componentsDetail/GeneralInfo/recommend/index";
import weightSizeInfo from "../componentsDetail/weightSizeInfo.vue";
import copySKU from "../componentsDetail/copySKU.vue";
import HeadFreight from "../componentsDetail/HeadFreight/index";
import { getCurrency } from "../api.js";
import { getOptions } from "@/api/index.js";
import {
  goodsCreate,
  goodsEdit,
  getDetail,
  getProductDetail,
  getSpu,
  getDraft,
  saveDraft,
  infringementDetection,
  review,
  delDraft,
  getSKUDetails,
} from "../api";
import { computed, nextTick, provide, reactive, ref, toRaw, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import useCommonStore from "@/store/modules/common";
import usePublicStore from "@/store/modules/public";
import { storeToRefs } from "pinia";
import action from "@/utils/action.js";
import InfringementDetection from "../componentsDetail/InfringementDetection.vue";
import { deepClone } from "@/utils/index";
import { scrollToError } from "@/hooks/formScroll.js";
import { queryBaseHeadFreightList } from "@/views/basics/reference-freight/api.js";
import { checkDuplicateAttributes } from "@/utils/product/index.js";
import { imageTypeText } from "../data.js";
import {
  clean_classified,
  classified_first,
  classified_second,
  classified_third,
  classified_auto_parts,
  classified_overseas_position,
} from "@/utils/product/data.js";

const commonStore = useCommonStore();
const publicStore = usePublicStore();
const { languageOptions, logisticsOptions } = storeToRefs(commonStore);

const route = useRoute();
const router = useRouter();

const data = reactive({
  form: {
    spu: "",
    spu_category: [],
    imitation_remark: "",
    need_photo: 1,
    need_processing: 2,
    recommended_level: "",
    brand_id: "",
    brand_type: 1,
    authentication: [],
    spu_cn_title: "",
    spu_en_title: "",
    specifications: "",
    spu_status: 1,
    goods_source: 1,
    goods_sku: [],
    goods_spu_sales_info: {
      suggested_sales_price: "",
      currency: "",
      currency_id: "",
      warehouse_id: "",
      suggested_header_channel: "",
      custom_specification: [{ name: "", value: "" }],
      competing_products_link: [""],
      spu_unit: "",
      packaging_method: "",
      plug_specification: "",
    },
    developer_id: "",
    purchaser_id: null,
    dev_reviewer_id: null,
    quality_inspector_id: null,
    img_processor_id: null,
    editor_id: null,
    goods_spu_prohibited_sales: [{ prohibited_platform: "", prohibited_site: "" }],
    goods_spu_remark: {
      dev_remark: "",
      purchase_remark: "",
      inspection_remark: "",
      packaging_remark: "",
    },
    goods_spu_certificate: [],
    goods_spu_gallery: [],
    goods_spu_customs: {
      cn_name: "",
      en_name: "",
      purpose: "",
      cn_material: "",
      en_material: "",
      declare_elements: "",
      customs_code: "",
      tax_rebate_rate: "",
      declare_price_usd: "",
      declare_unit: "",
      declare_link: "",
      declare_link_price_eur: "",
    },
    goods_spu_combination_sku: [],
    goods_spu_description: [
      {
        spu_title: "",
        detail_description: "",
        text_description: "",
        highlights_description: "",
        package_description: "",
        mobile_description: "",
        keyword: "",
        language_id: 1,
        language: "中文",
        language_code: "zh",
        show: true,
      },
      {
        spu_title: "",
        detail_description: "",
        text_description: "",
        highlights_description: "",
        package_description: "",
        mobile_description: "",
        keyword: "",
        language_id: 2,
        language: "英语",
        language_code: "en",
        show: true,
      },
    ],
    goods_spu_supplier: [],
    goods_spu_accessories: [],
    goods_spu_specification: [],
    dev_status: 0,
  },
  dialogVisible: false,
  errorMessage: "",
  handleType: null,
  spuId: null,
  sku: null,
  sku_id: null,
  activeName: "",
  generalactive: "Supplier",
  goods_spu_gallery: [],
  sku_product_type: null, // 产品类型
  add_sku_info: {}, // 新增 选择类型 传递信息
});
let {
  form,
  dialogVisible,
  errorMessage,
  handleType,
  spuId,
  sku,
  sku_id,
  activeName,
  generalactive,
  goods_spu_gallery,
  sku_product_type,
  add_sku_info,
} = toRefs(data);
const options = ref([]);

provide("options", options);
provide("form", form);
provide("handleType", handleType);
provide(
  "createSKU",
  computed(() => {
    return route.query?.type || null;
  })
);
provide(
  "creatSkuInfo",
  computed(() => {
    return creatSkuInfo.value;
  })
);
provide("sku_product_type", sku_product_type);
provide("add_sku_info", add_sku_info);

// 语言
const getLanguageList = async () => {
  commonStore.getLanguageList();
};
getLanguageList();

const changeAttribute = async () => {
  activeName.value = form.value.goods_sku[0]?.sku;
  // handleResize();
};

// 下拉数据
const fetchOption = async () => {
  const res = await getOptions({
    name: [
      "goods.GoodsSpu",
      "goods.GoodsSku",
      "goods.GoodsSkuSalesInfo",
      "goods.GoodsSkuSupplier",
      "goods.GoodsSkuAccessories",
      "goods.GoodsSkuSupplier",
      "gallery.GoodsSkuGalleryContents",
      "goods.GoodsSkuIdentificationProcessing",
      "goods.GoodsSkuCertificate",
    ],
  });
  options.value = res.data;
};

// 初始化默认产品图片一个标签
const initGallery = (isreturn = false) => {
  let obj = {
    custom_tag: "默认",
    spu: form.spu,
    spu_category: form.value.spu_category,
    spu_cn_title: form.value.spu_cn_title,
    contents: [],
  };
  imageTypeText.forEach((element, e) => {
    obj.contents.push({
      label: element.label,
      image_type: element.value,
      showType: 0,
      values: [],
    });
  });
  if (isreturn) {
    return [obj];
  } else {
    goods_spu_gallery.value = [obj];
  }
};

initGallery();

const initGalleryContents = () => {
  let contents = [];
  imageTypeText.forEach((element, e) => {
    contents.push({
      label: element.label,
      image_type: element.value,
      showType: 0,
      values: [],
    });
  });
  return contents;
};

// 初始化编辑多属性
const initSpecification = () => {
  let array = [
    {
      is_relation_img: 0,
      group_name: "颜色",
      loading: false,
      show: true,
      valueName: "",
      values: [
        {
          language_name: "中文",
          language_id: 1,
          language_code: "zh-chs",
          show: true,
          name: "颜色",
          language_values: [
            {
              language_id: 1,
              group: 1,
              spu_id: form.value.spu,
              name: "颜色",
              value: "",
            },
          ],
        },
        {
          language_name: "英语",
          language_code: "en",
          language_id: 2,
          show: true,
          name: "color",
          language_values: [
            {
              language_id: 2,
              group: 1,
              spu_id: form.value.spu,
              name: "颜色",
              value: "",
            },
          ],
        },
      ],
    },
    {
      is_relation_img: 0,
      group_name: "尺寸",
      loading: false,
      show: true,
      valueName: "",
      values: [
        {
          language_name: "中文",
          language_id: 1,
          language_code: "zh-chs",
          show: true,
          name: "尺寸",
          language_values: [
            {
              language_id: 1,
              group: 1,
              spu_id: form.value.spu,
              name: "尺寸",
              value: "",
            },
          ],
        },
        {
          language_name: "英语",
          language_code: "en",
          language_id: 2,
          show: true,
          name: "size",
          language_values: [
            {
              language_id: 2,
              group: 1,
              spu_id: form.value.spu,
              name: "尺寸",
              value: "",
            },
          ],
        },
      ],
    },
  ];
  let arr =
    languageOptions.value &&
    languageOptions.value.filter((item) => !(item.id === 1 || item.id === 2));
  arr &&
    arr.forEach((op) => {
      array.forEach((i) => {
        i.values.push({
          name: "",
          language_code: op.short_name,
          language_name: op.name,
          language_id: op.id,
          show: op.id == 10 ? true : false,
          language_values: [
            {
              language_id: op.id,
              group: 1,
              spu_id: form.value.spu,
              name: op.name,
              value: "",
            },
          ],
        });
      });
    });
  form.value.goods_spu_specification = array;
};

// 生成sku 单属性
const initSpecificationSKU = () => {
  let array = [
    {
      is_relation_img: 0,
      group_name: "颜色",
      loading: false,
      show: true,
      valueName: "",
      values: [
        {
          language_name: "中文",
          language_id: 1,
          language_code: "zh-chs",
          show: true,
          name: "颜色",
          language_values: [
            {
              language_id: 1,
              group: 1,
              spu_id: form.value.spu,
              name: "颜色",
              value: "",
            },
          ],
        },
        {
          language_name: "英语",
          language_code: "en",
          language_id: 2,
          show: true,
          name: "color",
          language_values: [
            {
              language_id: 2,
              group: 1,
              spu_id: form.value.spu,
              name: "颜色",
              value: "",
            },
          ],
        },
      ],
    },
    {
      is_relation_img: 0,
      group_name: "尺寸",
      loading: false,
      show: false,
      valueName: "",
      values: [
        {
          language_name: "中文",
          language_id: 1,
          language_code: "zh-chs",
          show: true,
          name: "尺寸",
          language_values: [
            {
              language_id: 1,
              group: 1,
              spu_id: form.value.spu,
              name: "尺寸",
              value: "",
            },
          ],
        },
        {
          language_name: "英语",
          language_code: "en",
          language_id: 2,
          show: true,
          name: "尺寸",
          language_values: [
            {
              language_id: 2,
              group: 1,
              spu_id: form.value.spu,
              name: "尺寸",
              value: "",
            },
          ],
        },
      ],
    },
  ];
  let arr =
    languageOptions.value &&
    languageOptions.value.filter((item) => !(item.id === 1 || item.id === 2));
  arr &&
    arr.forEach((op) => {
      array.forEach((i) => {
        i.values.push({
          group_name: op.name,
          language_code: op.short_name,
          language_name: op.name,
          language_id: op.id,
          show: op.id == 10 ? true : false,
          name: "",
          language_values: [
            {
              language_id: op.id,
              group: 1,
              spu_id: form.value.spu,
              name: op.name,
              value: "",
            },
          ],
        });
      });
    });
  return array;
};

const CertificateRef = ref();

const FlowRef = ref();
const spuInfoRef = ref();
const creatSkuInfo = ref({});
const queryDetail = async (type) => {
  if (type == "createSKU") {
    try {
      const res = await getProductDetail({
        productId: Number(spuId.value),
      });
      creatSkuInfo.value = JSON.parse(JSON.stringify(res?.data || {}));

      nextTick(async () => {
        const againData = res.data;
        form.value.product_id = Number(route.query?.productId);
        form.value.spu_category = againData.product_category.map((i) => Number(i));
        form.value.spu_cn_title = againData.product_title;
        form.value.dev_add_time = againData.create_time;
        form.value.productAttribute = {
          purchase_days: againData.purchase_days,
          gross_weight_g: againData.product_fee[0]?.gross_weight_g,
          purchase_price: againData.product_fee[0]?.purchase_cost,
          packing_size_cm: againData.product_fee[0]?.packing_specification,
          dev_remark: againData.development_remark,
          dev_remark_appendix: againData.dev_remark_appendix,
        };
        form.value.dev_status = 0;

        // 开发任务维护物流属性，如无则默认普货
        if (againData.logistic_attr) {
          form.value.logistics_attributes = creatSkuInfo.value.logistic_attr;
          form.value.logistics_attributes_name = creatSkuInfo.value.logistic_attr_text;
        } else {
          const logistics = logisticsOptions.value.find((i) => i.label == "普货");
          form.value.logistics_attributes = logistics?.value;
          form.value.logistics_attributes_name = logistics?.label;
        }

        await spuInfoRef.value.changeCategory();
        // 生成SKU单属性/多属性处理
        if (againData.attribute_type == 1) {
          form.value.goods_spu_specification = initSpecificationSKU();
          await multiAttributeRef.value.getCreatSku();
          setTimeout(async () => {
            await syncName();

            if (form.value.goods_sku.length) {
              form.value.goods_sku.forEach((i) => {
                i.developer_id = againData.developer_id;
              });
            }
          }, 1000);
        } else if (againData.attribute_type == 2) {
          const spu_specification = againData.specification.length
            ? againData.specification
                .filter((i) => i.value.length)
                .map((item, index) => {
                  const key_value = [];
                  if (item.value && item.value.length) {
                    item.value.map((i) => {
                      key_value.push({
                        language_id: 1,
                        language_name: "中文",
                        name: i,
                        value: i,
                        group: index + 1,
                      });
                    });
                  }

                  item.values = [
                    {
                      language_id: 1,
                      language_name: "中文",
                      group: index + 1,
                      name: item.label,
                      language_values: [...key_value],
                    },
                  ];
                  return {
                    group_name: item.label,
                    values: item.values,
                  };
                })
            : [];
          console.log("spu_specification");
          console.log(spu_specification);

          form.value.goods_spu_specification = matchSpecification(spu_specification);
          await multiAttributeRef.value.editRef.open();
        }
      });
      settingWeight();
    } catch (e) {
      throw Error(e);
    }
  } else if (type == "copy") {
    try {
      const res = await getDetail({
        spuId: spuId.value,
      });
      let copyDealData = res.data;
      copyDealData.recommended_level = null;
      copyDealData.goods_sku = copyDealData?.goods_sku?.map((i) => ({
        ...i,
        product_level: null,
      }));
      nextTick(() => {
        let againData = matchCopyData(copyDealData);
        againData.goods_spu_specification = againData.goods_spu_specification?.length
          ? matchSpecification(againData.goods_spu_specification)
          : creatSpecification(againData.goods_sku[0].sku_specification);
        let newList = deepClone(againData.goods_spu_specification);
        let list = newList.map((i) => {
          i.values.forEach((j) => {
            if (j.language_id == 2) {
              i.en_value = j.language_values.map((k) => k.value);
              i.first_value = j.language_values.map((k) => k.first_value);
              i.en_name = j.name;
            }
            if (j.language_id == 1) {
              i.cn_value = j.language_values.map((k) => k.value);
              i.cn_name = j.name;
            }
          });
          i.first_value = i.first_value?.length ? i.first_value : i.en_value;
          i.name = i.group_name;
          delete i.values;
          return i;
        });
        getSpu({ spu: "", productCategory: againData.spu_category, attributes: [] }).then(
          (res1) => {
            againData.spu = res1.data.spu;
            let data = {
              spu: againData.spu,
              productCategory: againData.spu_category,
              attributes: list,
              recreate: true,
            };
            getSpu(data).then((res2) => {
              const copyCondition = publicStore.copyCondition;
              // 根据条件复制供应商信息
              if (copyCondition && !copyCondition.spu_cn_title) {
                againData.spu_cn_title = "";
              }
              res2?.data?.skus?.forEach((i, j) => {
                if (againData.goods_sku[j]) {
                  againData.goods_sku[j].sku = i.sku;
                  againData.goods_sku[j].custom_sku = i.custom_sku;
                  againData.goods_sku[j].id = "";
                  againData.goods_sku[j].sai_he_sku = "";
                  againData.goods_sku[j].is_contains_accessories = "";
                  againData.goods_sku[j].main_attribute = 1;
                  againData.goods_sku[j].latest_purchase_price = "";
                  againData.goods_sku[j].lowest_purchase_price = "";
                  againData.goods_sku[j].average_purchase_price = "";
                  againData.goods_sku[j].logistics_reviewer_id = 0;
                  againData.goods_sku[j].goods_sku_relation_old = {};
                  if (!copyCondition) {
                    againData.goods_sku[j].goods_sku_supplier = againData.goods_sku[
                      j
                    ].goods_sku_supplier.map((k) => {
                      k.id = "";
                      return k;
                    });
                  } else if (copyCondition && copyCondition.supplier_info) {
                    againData.goods_sku[j].goods_sku_supplier = againData.goods_sku[
                      j
                    ].goods_sku_supplier.map((k) => {
                      k.id = "";
                      const goods_sku_customs = k.goods_sku_customs;
                      // 根据条件复制报关信息
                      if (!copyCondition.goods_sku_customs) {
                        k.goods_sku_customs = {
                          goods_sku_customs_info: [
                            {
                              customs_currency: "USD",
                            },
                          ],
                        };
                      }
                      // 根据条件复制申报要素
                      if (copyCondition.declare_elements_list) {
                        k.goods_sku_customs.declare_elements_list =
                          goods_sku_customs.declare_elements_list;
                        k.goods_sku_customs.declare_elements =
                          goods_sku_customs.declare_elements;
                      } else {
                        k.goods_sku_customs.declare_elements_list = [];
                        goods_sku_customs.declare_elements = "";
                      }
                      // 根据条件复制欧英代产品资料
                      if (!copyCondition.goods_sku_trade_agent) {
                        k.goods_sku_trade_agent = [];
                      }
                      // 根据条件复制产品加工标识
                      if (!copyCondition.goods_sku_identification_processing) {
                        k.goods_sku_identification_processing = [];
                      }

                      return k;
                    });
                  } else {
                    againData.goods_sku[j].goods_sku_supplier = [];
                  }
                  if (
                    clean_classified.includes(
                      againData.spu_category ? againData.spu_category[0] : ""
                    )
                  ) {
                    againData.goods_sku[j].clean_product_status = 1;
                  } else {
                    againData.goods_sku[j].clean_product_status = "";
                  }

                  // 根据条件复制供应商信息
                  // if (copyCondition && !copyCondition.supplier_info) {
                  //   againData.goods_sku[j].goods_sku_supplier = [];
                  // }
                  // 根据条件复制辅料信息
                  if (copyCondition && !copyCondition.ingredient_info) {
                    againData.goods_sku[j].goods_sku_accessories = [];
                  }
                  // 根据条件复制推荐平台站点
                  if (copyCondition && !copyCondition.platform_site_info) {
                    againData.goods_sku[j].goods_sku_recommended_platform = [];
                  }
                  // 根据条件复制开发备注
                  if (copyCondition && !copyCondition.dev_remark) {
                    againData.goods_sku[j].goods_sku_remark.dev_remark = "";
                    againData.goods_sku[j].goods_sku_remark.dev_remark_appendix = [];
                  }
                  // 根据条件复制编辑备注
                  if (copyCondition && !copyCondition.edit_remark) {
                    againData.goods_sku[j].goods_sku_remark.edit_remark = "";
                    againData.goods_sku[j].goods_sku_remark.edit_remark_appendix = [];
                  }
                  // 根据条件复制采购收货备注
                  if (copyCondition && !copyCondition.purchase_remark) {
                    againData.goods_sku[j].goods_sku_remark.purchase_remark = "";
                    againData.goods_sku[j].goods_sku_remark.purchase_remark_appendix = [];
                  }
                  // 根据条件复制仓库打包备注
                  if (copyCondition && !copyCondition.packaging_remark) {
                    againData.goods_sku[j].goods_sku_remark.packaging_remark = "";
                    againData.goods_sku[
                      j
                    ].goods_sku_remark.packaging_remark_appendix = [];
                  }
                  // 根据条件复制仓库质检备注
                  if (copyCondition && !copyCondition.inspection_remark) {
                    againData.goods_sku[j].goods_sku_remark.inspection_remark = "";
                    againData.goods_sku[
                      j
                    ].goods_sku_remark.inspection_remark_appendix = [];
                  }
                }
              });
              // againData.is_push_to_saihe = 1;
              againData.developer_id = window.userInfo.user.user_id || "";
              againData.product_manage_id = window.userInfo.user.user_id || "";

              againData.spu_status = 1;
              againData.spu_sales_status = 1;
              againData.spu_supply_status = 1;
              if (
                clean_classified.includes(
                  againData.spu_category ? againData.spu_category[0] : ""
                )
              ) {
                againData.spu_clean_product_status = 1;
              } else {
                againData.spu_clean_product_status = "";
              }

              // 删除时间、人员
              delete againData.create_time;
              delete againData.create_user;
              delete againData.create_user_text;
              delete againData.dev_add_time;
              delete againData.dev_review_remark;
              delete againData.dev_review_time;
              delete againData.dev_reviewer_id;
              delete againData.dev_reviewer_text;
              delete againData.dev_status_text;
              delete againData.developer_text;

              //复制的进入新增页面后，产品类型需锁定，不支持调整
              sku_product_type.value = 4;

              againData.dev_status = 0;
              againData.goods_from = 1;
              againData.id = null;
              form.value = againData;
              activeName.value = againData.goods_sku[0]?.sku;
              settingWeight();
            });
          }
        );
      });
    } catch (e) {
      throw Error(e);
    }
  } else if (type == "edit") {
    try {
      const res = await getDetail({
        spuId: spuId.value,
        fromEdit: true,
      });
      let againData = res.data;
      againData.goods_sku = againData.goods_sku.map((i) => {
        i.goods_sku_gallery =
          i.goods_sku_gallery && i.goods_sku_gallery.length
            ? i.goods_sku_gallery.map((j) => {
                if (j.contents.length == 0) {
                  j.contents = initGalleryContents();
                } else {
                  j.contents = matchAndAdd(
                    goods_spu_gallery.value[0].contents,
                    j.contents
                  );
                  j.contents = j.contents.sort((a, b) => a.image_type - b.image_type);
                }
                return j;
              })
            : initGallery(true);
        i.goods_sku_sales_info = i.goods_sku_sales_info || {
          brand_id: "",
          brand_type: 1,
          suggested_sales_price: "",
          currency: "",
          currency_id: 158,
          currency_name: "USD",
          warehouse_id: "",
          logistics_attributes: "",
          suggested_header_channel: "",
          custom_specification: [{ name: "", value: "" }],
          competing_products_link: [""],
          spu_unit: "",
          packaging_method: "",
          plug_specification: "",
          goods_spu_prohibited_sales: [{ prohibited_platform: "", prohibited_site: "" }],
          is_new_product: 1,
          is_seasonal_product: 0,
        };
        i.goods_sku_prohibited_sales = i.goods_sku_prohibited_sales?.length
          ? i.goods_sku_prohibited_sales
          : [
              {
                platform_name: "",
                site_code: "",
                platform_id: "",
              },
            ];
        i.goods_sku_authentication = i.goods_sku_authentication?.length
          ? i.goods_sku_authentication
          : [
              {
                country_id: "",
                country_name: "",
                authentication_type: "",
                authentication_name: "",
              },
            ];
        i.goods_sku_remark = i.goods_sku_remark || {
          dev_remark: "",
          edit_remark: "",
          purchase_remark: "",
          inspection_remark: "",
          packaging_remark: "",
        };
        i.goods_sku_customs = i.goods_sku_customs || {
          cn_name: "",
          en_name: "",
          purpose: "",
          cn_material: "",
          en_material: "",
          declare_elements: "",
          customs_code: "",
          tax_rebate_rate: "",
          declare_price_usd: "",
          declare_unit: "",
          declare_link: "",
          declare_link_price_eur: "",
        };
        i.goods_sku_sales_info.custom_specification = i.goods_sku_sales_info
          .custom_specification?.length
          ? i.goods_sku_sales_info.custom_specification
          : [{ name: "", value: "" }];
        i.goods_sku_recommended_platform = i.goods_sku_recommended_platform || [];
        i.goods_sku_title =
          i.goods_sku_title &&
          i.goods_sku_title.map((j) => {
            j.show = true;
            return j;
          });
        i.main_img = i.attr_img;
        return i;
      });
      againData.goods_spu_specification = matchSpecification(
        againData.goods_spu_specification
      );
      form.value = againData;
      activeName.value = form.value.goods_sku[0]?.sku;
    } catch (e) {
      throw Error(e);
    }
  }
};

// 初始化处理数据
const matchData = (data) => {
  data.goods_sku = data.goods_sku.map((i) => {
    i.goods_sku_gallery =
      i.goods_sku_gallery && i.goods_sku_gallery.length
        ? i.goods_sku_gallery.map((j) => {
            if (j.contents.length == 0) {
              j.contents = initGalleryContents();
            } else {
              j.contents = matchAndAdd(goods_spu_gallery.value[0].contents, j.contents);
              j.contents = j.contents.sort(
                (a, b) => gallerySort(a.image_type) - gallerySort(b.image_type)
              );
            }
            return j;
          })
        : initGallery(true);

    i.goods_sku_sales_info = i.goods_sku_sales_info || {
      brand_id: "",
      brand_type: 1,
      suggested_sales_price: "",
      currency: "",
      currency_id: 158,
      currency_name: "USD",
      warehouse_id: "",
      logistics_attributes: "",
      suggested_header_channel: "",
      custom_specification: [{ name: "", value: "" }],
      competing_products_link: [""],
      spu_unit: "",
      packaging_method: "",
      plug_specification: "",
      goods_spu_prohibited_sales: [{ prohibited_platform: "", prohibited_site: "" }],
    };
    i.goods_sku_prohibited_sales = i.goods_sku_prohibited_sales?.length
      ? i.goods_sku_prohibited_sales
      : [
          {
            platform_name: "",
            site_code: "",
            platform_id: "",
          },
        ];
    i.goods_sku_authentication = i.goods_sku_authentication?.length
      ? i.goods_sku_authentication
      : [
          {
            country_id: "",
            country_name: "",
            authentication_type: "",
            authentication_name: "",
          },
        ];

    i.goods_sku_remark = i.goods_sku_remark || {
      dev_remark: "",
      purchase_remark: "",
      inspection_remark: "",
      packaging_remark: "",
    };
    i.goods_sku_customs = i.goods_sku_customs || {
      cn_name: "",
      en_name: "",
      purpose: "",
      cn_material: "",
      en_material: "",
      declare_elements: "",
      customs_code: "",
      tax_rebate_rate: "",
      declare_price_usd: "",
      declare_unit: "",
      declare_link: "",
      declare_link_price_eur: "",
    };
    i.goods_sku_sales_info.custom_specification = i.goods_sku_sales_info
      .custom_specification?.length
      ? i.goods_sku_sales_info.custom_specification
      : [{ name: "", value: "" }];
    i.goods_sku_recommended_platform = i.goods_sku_recommended_platform || [];
    i.goods_sku_title =
      i.goods_sku_title &&
      i.goods_sku_title.map((j) => {
        j.show = true;
        return j;
      });
    i.main_img = i.attr_img;
    return i;
  });
  return data;
};

// 处理复制数据
const matchCopyData = (data) => {
  if (sku_id.value) {
    data.goods_sku = data.goods_sku.filter((item) => {
      if (item.id == sku_id.value) {
        item.product_status = 1;
        item.sales_status = 1;
        item.supply_status = 1;
        item.dev_status = 0;
        return item;
      }
    });
  }
  const copyCondition = publicStore.copyCondition;
  data.goods_sku = data.goods_sku.map((i) => {
    i.goods_sku_gallery =
      (!copyCondition || (copyCondition && copyCondition.sku_picture)) &&
      i.goods_sku_gallery &&
      i.goods_sku_gallery.length
        ? removeArraysIds(
            i.goods_sku_gallery.map((j) => {
              if (j.contents.length == 0) {
                j.contents = initGalleryContents();
              } else {
                j.contents = matchAndAdd(goods_spu_gallery.value[0].contents, j.contents);
                j.contents = j.contents.sort(
                  (a, b) => gallerySort(a.image_type) - gallerySort(b.image_type)
                );
              }
              return j;
            })
          )
        : initGallery(true);

    i.goods_sku_sales_info = (i.goods_sku_sales_info &&
      removeIds(i.goods_sku_sales_info)) || {
      brand_id: "",
      brand_type: 1,
      suggested_sales_price: "",
      currency: "",
      currency_id: 158,
      currency_name: "USD",
      warehouse_id: "",
      logistics_attributes: "",
      suggested_header_channel: "",
      custom_specification: [{ name: "", value: "" }],
      competing_products_link: [""],
      spu_unit: "",
      packaging_method: "",
      plug_specification: "",
      goods_spu_prohibited_sales: [{ prohibited_platform: "", prohibited_site: "" }],
    };
    i.goods_sku_prohibited_sales = i.goods_sku_prohibited_sales?.length
      ? removeArrayIds(i.goods_sku_prohibited_sales)
      : [
          {
            platform_name: "",
            site_code: "",
            platform_id: "",
          },
        ];
    i.goods_sku_authentication = i.goods_sku_authentication?.length
      ? removeArrayIds(i.goods_sku_authentication)
      : [
          {
            country_id: "",
            country_name: "",
            authentication_type: "",
            authentication_name: "",
          },
        ];
    i.goods_sku_sell_month = i.goods_sku_sell_month?.length
      ? removeArrayIds(i.goods_sku_sell_month)
      : [
          {
            country: [],
            hot_sell_start_month: "",
            hot_sell_end_month: "",
            remark: "",
          },
        ];
    // i.goods_sku_sell_month = i.goods_sku_sell_month?.length
    //   ? i.goods_sku_sell_month
    //   : [
    //       {
    //         country: [],
    //         hot_sell_start_month: "",
    //         hot_sell_end_month: "",
    //         remark: "",
    //       },
    //     ];
    i.goods_sku_remark = (i.goods_sku_remark && removeIds(i.goods_sku_remark)) || {
      dev_remark: "",
      purchase_remark: "",
      inspection_remark: "",
      packaging_remark: "",
    };
    i.goods_sku_customs = (i.goods_sku_customs && removeIds(i.goods_sku_customs)) || {
      cn_name: "",
      en_name: "",
      purpose: "",
      cn_material: "",
      en_material: "",
      declare_elements: "",
      customs_code: "",
      tax_rebate_rate: "",
      declare_price_usd: "",
      declare_unit: "",
      declare_link: "",
      declare_link_price_eur: "",
    };
    i.goods_sku_sales_info.custom_specification = i.goods_sku_sales_info
      .custom_specification?.length
      ? i.goods_sku_sales_info.custom_specification
      : [{ name: "", value: "" }];
    i.goods_sku_title =
      i.goods_sku_title &&
      removeArrayIds(
        i.goods_sku_title.map((j) => {
          j.show = true;
          return j;
        })
      );
    i.goods_sku_certificate = i.goods_sku_certificate?.length
      ? removeArrayIds(i.goods_sku_certificate)
      : [];
    i.goods_sku_description = i.goods_sku_description?.length
      ? removeArrayIds(i.goods_sku_description)
      : [];
    i.goods_sku_recommended_platform = i.goods_sku_recommended_platform?.length
      ? removeArrayIds(i.goods_sku_recommended_platform)
      : [];
    i.goods_sku_accessories = i.goods_sku_accessories?.length
      ? removeArrayIds(i.goods_sku_accessories, i.sku || i.custom_sku)
      : [];
    i.goods_sku_combination_sku = [];
    i.main_img = i.attr_img;
    i.main_attribute = i.main_attribute;
    i.dev_add_time = "";
    i.dev_review_time = "";
    i.logistics_review_time = "";
    return i;
  });
  data.goods_spu_specification = matchSpecification(data.goods_spu_specification);
  return data;
};

const gallerySort = (type) => {
  if (type == 3) {
    return 0;
  } else {
    return type;
  }
};

const matchAndAdd = (array1, array2) => {
  for (var i = 0; i < array1.length; i++) {
    var isDuplicate = false;
    for (var j = 0; j < array2.length; j++) {
      if (array1[i].image_type === array2[j].image_type) {
        isDuplicate = true;
        break;
      }
    }
    if (!isDuplicate) {
      array2.push(array1[i]);
    }
  }
  return array2;
};

const matchSpecification = (goods_spu_specification) => {
  const list = goods_spu_specification.map((spec) => {
    const updatedValues = [];

    spec.values.forEach((valueObj) => {
      const copyValue = { ...valueObj, show: true };
      updatedValues.push(copyValue);
    });

    const existingLanguageIds = new Set(
      updatedValues.map((valueObj) => valueObj.language_id)
    );

    if (languageOptions && languageOptions.value) {
      languageOptions.value.forEach((d) => {
        if (!existingLanguageIds.has(d.id)) {
          const copyValue = {
            language_id: d.id,
            language_name: d.name,
            language_code: d.short_name,
            is_relation_img: 0,
            show: d.id === 1 || d.id === 2 || d.id === 10,
            name: "",
            language_values: spec.values[0].language_values.map((v) => ({
              ...v,
              language_id: d.id,
              language_name: d.name,
              language_code: d.short_name,
              id: "",
              value: "",
            })),
          };
          updatedValues.push(copyValue);
        } else {
          updatedValues.forEach((valueObj) => {
            if (valueObj.language_id === d.id) {
              valueObj.show = d.id === 1 || d.id === 2 || d.id === 10;
            }
          });
        }
      });
    }

    spec.values = updatedValues.sort((a, b) => a.language_id - b.language_id);
    return spec;
  });

  return list;
};

const DdescribeRef = ref();
// 修改spu 需要重置sku
const initsku = () => {
  initGallery();
  settingWeight();

  if (form.value.goods_sku.length > 0) {
    form.value.goods_sku.forEach((i) => {
      i = replaceWithSKU(i, i.sku);
    });
    activeName.value = form.value.goods_sku[0]?.sku;
  }
};

const replaceWithSKU = (source, sku) => {
  for (const key in source) {
    if (source.hasOwnProperty(key)) {
      if (typeof source[key] === "object" && source[key] !== null) {
        // 如果属性值是对象且不为 null，递归调用 deepCopyWithPreserveId
        source[key] = replaceWithSKU(source[key], sku);
      } else {
        source["sku"] = sku;
      }
    }
  }
  return source;
};

const back = () => {
  ElMessageBox.confirm("确认返回将关闭当前页面", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    action.setGlobalState({
      changeMicoTabsPath: {
        type: "closeActiveTab",
      },
    });
  });
};

// 新增、编辑
const peopleInfoRef = ref();
const multiAttributeRef = ref();
const weightSizeInfoRefs = ref([]);
const peopleInfoRefs = ref([]);
const pictureRefs = ref([]);
const supplierRefs = ref();
const headFreightRefs = ref();

watch(
  () => form.value?.goods_sku?.length,
  (val) => {
    updateSellInfoRefs();
  }
);
const updateSellInfoRefs = () => {
  weightSizeInfoRefs.value = form.value?.goods_sku?.map((_, index) =>
    ref(`weightSizeInfoRef${index}`)
  );
  pictureRefs.value = form.value?.goods_sku?.map((_, index) => ref(`pictureRef${index}`));
  supplierRefs.value = form.value?.goods_sku?.map((_, index) =>
    ref(`supplierRef${index}`)
  );
  peopleInfoRefs.value = form.value?.goods_sku?.map((_, index) =>
    ref(`peopleInfoRef${index}`)
  );
  headFreightRefs.value = form.value?.goods_sku?.map((_, index) =>
    ref(`headFreightRef${index}`)
  );
};

const weightSize_permission = computed(() => {
  return (window.BTN_AUTH || []).includes("/goods/task/product/weight-size-info");
});

const supplierRef = ref();
const save = async () => {
  console.log("form.value");
  console.log(form.value);

  await spuInfoRef.value.validate();
  // await peopleInfoRef.value.validate()
  await multiAttributeRef.value.validate();
  let flag = true;
  for (let i = 0; i < form?.value?.goods_sku?.length; i++) {
    activeName.value = form.value.goods_sku[i].sku;
    await new Promise((resolve) => setTimeout(resolve, 0)); // 等待下一个事件循环
    await nextTick(async () => {
      try {
        if (
          !form.value?.goods_sku[i]?.gross_weight_g ||
          !form.value?.goods_sku[i]?.net_weight_g
        ) {
          scrollToError(document.querySelector(".weightSizeInfo"));
          ElMessage.warning("产品毛重和净重不能为空!");
          throw new Error("这是一个错误");
        }
        if (!form.value?.goods_sku[i]?.attr_img) {
          scrollToError(document.querySelector(".pictureId"));
          ElMessage.warning("产品图片中至少需要一张图片作为主图!");
          throw new Error("这是一个错误");
        }

        if (
          !form?.value?.goods_sku[i]?.goods_sku_supplier?.length &&
          form?.value?.goods_sku[i]?.is_combination != 1
        ) {
          scrollToError(document.querySelector(".GeneralInfoRef"));
          ElMessage.warning("请至少添加一条供应商信息!");
          throw new Error("这是一个错误");
        }
        // 一级分类=汽摩配类（新增一级分类），产品类型=正常/配件
        if (
          classified_auto_parts.includes(
            form.value.spu_category ? form.value.spu_category[0] : ""
          ) &&
          [1, 2].includes(form.value?.goods_sku[i]?.sku_product_type)
        ) {
          if (form.value?.goods_sku[i]?.goods_sku_recommended_platform.length == 0) {
            scrollToError(document.querySelector(".platformSite"));
            ElMessage.warning("产品=正常/配件,推荐平台/站点至少维护一行!");
            throw new Error("这是一个错误");
          }
        }
        const findIndex = form.value?.goods_sku[
          i
        ]?.goods_sku_recommended_platform.findIndex((i) => i.platform_name == "amazon");
        if (
          classified_overseas_position.includes(
            form.value.spu_category ? form.value.spu_category[0] : ""
          ) ||
          (findIndex == -1 &&
            classified_auto_parts.includes(
              form.value.spu_category ? form.value.spu_category[0] : ""
            ) &&
            weightSize_permission.value)
        ) {
          const { length, width, height } = form.value?.goods_sku[i]?.packing_size_cm;
          const dimensions = [length, width, height].sort((a, b) => a - b);
          if (!(dimensions[0] > 0 && dimensions[1] >= 10 && dimensions[2] >= 15)) {
            const sku_ids = form.value?.goods_sku[i]?.goods_sku_accessories
              .filter((i) => !i.delete)
              .map((i) => i.accessory_sku_id);
            const is_satisfy = await checkSKUAccessories(sku_ids);
            if (!is_satisfy) {
              scrollToError(document.querySelector(".weightSizeInfo"));
              ElMessage.warning(
                "海外仓SKU的包装尺寸或者绑定的辅料包装尺寸，至少有一边>=10cm;一边>=15cm且必须>0，当前SKU未满足，请核实；若有疑问可咨询物流部"
              );
              throw new Error("这是一个错误");
            }
          }
        }
        if (
          form.value?.goods_sku[i]?.goods_sku_relation_old?.is_change_sku == 1 &&
          !form.value?.goods_sku[i]?.goods_sku_relation_old?.old_sku
        ) {
          scrollToError(document.querySelector(".SKUInfo"));
          ElMessage.warning("是否切换SKU=是，旧SKU必填");
          throw new Error("这是一个错误");
        }
      } catch (error) {
        flag = false;
        return;
      }
    });
    if (!flag) return;
  }
  if (!flag) return;
  const newForm = deepClone(form.value);
  const result = checkDuplicateAttributes(newForm.goods_sku);
  if (result.duplicate) {
    const repetition = Object.values(result.attributes);
    ElMessage.warning(`发现重复属性: ${repetition.join(",")} `);
    return;
  }

  if (result.nullValue) {
    ElMessage.warning(`SKU属性值不能为空，请检查`);
    return;
  }
  newForm.goods_sku = newForm?.goods_sku?.map((item) => {
    item.goods_sku_description =
      item?.goods_sku_description?.filter((j) => {
        if (j.show != false) {
          return j;
        }
      }) || [];
    item.goods_sku_title =
      item.goods_sku_title &&
      item.goods_sku_title.filter((i) => {
        if (i.show && i.language_id) {
          return i;
        }
      });
    item.goods_sku_gallery = item.goods_sku_gallery.map((i) => {
      i.contents = i.contents
        .filter((j) => j.values.length > 0)
        .map((k) => {
          k.values = k.values.map((v, w) => {
            v.sort = w;
            return v;
          });
          return k;
        });
      return i;
    });
    item.goods_sku_remark.edit_remark =
      item.goods_sku_remark.edit_remark == "<p><br></p>"
        ? ""
        : item.goods_sku_remark.edit_remark;
    item.goods_sku_remark.inspection_remark =
      item.goods_sku_remark.inspection_remark == "<p><br></p>"
        ? ""
        : item.goods_sku_remark.inspection_remark;
    item.goods_sku_prohibited_sales =
      item.goods_sku_prohibited_sales &&
      item.goods_sku_prohibited_sales.filter((j) => {
        if (j.platform_id && j.site_code) {
          return j;
        }
      });
    item.goods_sku_authentication = item.goods_sku_authentication.filter((j) => {
      if (j.country?.length > 0 && j.authentication_name) {
        return j;
      }
      if (j.id && j.country?.length == 0 && !j.authentication_name) {
        j.delete = 1;
        return j;
      }
    });
    item.goods_sku_accessories = item?.goods_sku_accessories?.map((j) => {
      if (!j.sku) {
        j.sku = "";
      }
      return j;
    });
    item.gross_weight_g = item.gross_weight_g || 0;
    item.net_weight_g = item.net_weight_g || 0;
    item.packing_weight_g = item.packing_weight_g || 0;
    item.packing_size_cm = {
      length: item.packing_size_cm.length || 0,
      width: item.packing_size_cm.width || 0,
      height: item.packing_size_cm.height || 0,
    };
    item.product_size_cm = {
      length: item.product_size_cm.length || 0,
      width: item.product_size_cm.width || 0,
      height: item.product_size_cm.height || 0,
    };
    item.packing_qty_size_cm = {
      length: item.packing_qty_size_cm.length || 0,
      width: item.packing_qty_size_cm.width || 0,
      height: item.packing_qty_size_cm.height || 0,
    };
    item.packing_gross_weight_kg = item.packing_gross_weight_kg || 0;
    item.cabinets_qty = item.cabinets_qty || 0;
    item.packing_qty = item.packing_qty || 0;
    item.goods_sku_head_freight = item.goods_sku_head_freight
      ?.filter((j) => {
        if (j.id || j.single_freight || j.single_tax_fee) {
          return j;
        }
      })
      .map((k) => {
        return {
          id: k.id,
          base_head_freight_id: k.base_head_freight_id,
          single_freight: k.single_freight || 0,
          single_tax_fee: k.single_tax_fee || 0,
        };
      });

    item.goods_sku_supplier = item.goods_sku_supplier.map((i) => {
      if (i.goods_sku_customs?.goods_sku_customs_info?.length) {
        i.goods_sku_customs.goods_sku_customs_info = i.goods_sku_customs.goods_sku_customs_info.map(
          (j) => {
            j.customs_price = j.customs_price || 0;
            j.clearance_price = j.clearance_price || 0;
            return j;
          }
        );
        return i;
      } else {
        return i;
      }
    });
    item.goods_sku_sell_month = item.goods_sku_sell_month.filter((i) => {
      return !(
        Array.isArray(i.country) &&
        i.country.length === 0 &&
        !i.hot_sell_start_month &&
        !i.hot_sell_end_month
      );
    });
    return item;
  });

  newForm.goods_spu_specification = newForm?.goods_spu_specification
    ?.filter((j) => {
      if (j.show != false) {
        return j;
      }
    })
    ?.map((i) => {
      i.values =
        i.values.length &&
        i.values.filter((i) => {
          if (i.show && i.language_id && i.name) {
            return i;
          }
        });
      return i;
    });
  const resquentFun = newForm.id ? goodsEdit : goodsCreate;
  resquentFun(newForm)
    .then(async (res) => {
      ElMessage.success(res.message);
      await delDraft();
      if (res.data.spu_id) {
        spuId.value = res.data.spu_id;
        // router.push({
        //   path: "/task/product/edit",
        //   query: {
        //     spuId: spuId.value,
        //     type: "edit",
        //   },
        // });
        // action.setGlobalState({
        //   changeMicoTabsPath: {
        //     type: "closeActiveTab",
        //   },
        // });
        const navigationResult = await router.push({
          path: "/task/product/edit",
          query: {
            spuId: spuId.value,
            type: "edit",
          },
        });

        // 检查导航是否成功
        if (navigationResult === undefined) {
          // 导航成功
          action.setGlobalState({
            changeMicoTabsPath: {
              type: "closeActiveTab",
            },
          });
        } else {
          // 导航失败
          ElMessage.error("导航到编辑页面时发生错误，请稍后再试。");
        }
        return;
      }
      handleType.value = "edit";
      initGallery();
      queryDetail("edit");
    })
    .catch((err) => {
      if (err.code == 20002) {
        errorMessage.value = err.message;
        dialogVisible.value = true;
      }
    });
};

const confirmNew = () => {
  dialogVisible.value = false;
  queryDetail("edit");
};

const confirmCover = () => {
  form.value.confirm_cover = true;
  dialogVisible.value = false;
  save();
};

// 锚点
const sideDataref = reactive({
  sideData: [
    {
      label: "SPU信息",
      name: "top",
    },
    {
      label: "多属性设置",
      name: "multiattribute",
    },
    {
      label: "SKU基础信息",
      name: "SKUInfo",
      offset: true,
    },
    {
      label: "SKU人员信息",
      name: "peopleInfo",
      offset: true,
    },
    {
      label: "SKU重量尺寸",
      name: "weightSizeInfo",
      offset: true,
    },
    {
      label: "SKU图片",
      name: "pictureId",
      offset: true,
    },
    {
      label: "SKU备注",
      name: "SKURemark",
      offset: true,
    },
    {
      label: "SKU证书/文件",
      name: "certificateFile",
      offset: true,
    },
    {
      label: "SKU推荐平台/站点",
      name: "platformSite",
      offset: true,
    },
    {
      label: "SKU综合信息",
      name: "GeneralInfoRef",
      offset: true,
    },
    {
      label: "保存/审核",
      name: "bottom",
      offset: true,
    },
  ],
});

const { sideData } = toRefs(sideDataref);

const filteredSKUItems = computed(() => {
  if (form.value.goods_sku?.length) {
    return sideData.value;
  } else {
    return sideData.value.slice(0, 3);
  }
});

const scrollPosition = reactive({
  top: 0,
  activeModule: "top",
  isTopBottom: "top",
});

const computedHeight = (e) => {
  if (e.currentTarget.scrollTop <= 1) {
    scrollPosition.isTopBottom = "top";
  } else if (
    e.currentTarget.scrollTop + e.currentTarget.clientHeight >=
    e.currentTarget.scrollHeight
  ) {
    scrollPosition.isTopBottom = "bottom";
  } else {
    scrollPosition.isTopBottom = "";
  }
};

const scrollContainer = ref();

const handleScroll = (event) => {
  let height = document.getElementById("scrollContainer").scrollTop;
  let heightSKu = document.querySelector(`#SKUOffsetTop`).offsetTop + 40;
  if (height >= heightSKu) {
    affixtab.value = form.value.goods_sku.length > 1 ? true : false;
  } else {
    affixtab.value = false;
  }
  scrollPosition.top = event.target.scrollTop;
  computedHeight(event);
  updateActiveModule();
};
const affixtab = ref(false);
const scrollTop = (selector, isOffset = false) => {
  nextTick(async () => {
    const element = document.querySelector(`#${selector}`);
    const offset = isOffset ? 45 : 0;
    if (element) {
      const height = element.offsetTop - offset;
      const container = document.querySelector("#scrollContainer");
      container.scrollTo({
        top: height,
        behavior: "smooth",
      });
    } else {
      console.warn(`Element with ID '${selector}' not found.`);
    }
  });
};

const updateActiveModule = () => {
  const containerTop = document.getElementById("scrollContainer").offsetTop + 45;
  const scrollPositionTop = scrollPosition.top;
  for (let i = 0; i < filteredSKUItems.value.length; i++) {
    const module = filteredSKUItems.value[i];
    const anchorElement = document.getElementById(module.name).offsetTop;
    const offset = module.offset ? -100 : 0;
    if (
      scrollPositionTop >= anchorElement + offset - containerTop &&
      (i === filteredSKUItems.value.length - 1 ||
        scrollPositionTop <
          (document.getElementById(filteredSKUItems.value[i + 1].name)?.offsetTop ||
            offset + 20) +
            offset -
            containerTop)
    ) {
      scrollPosition.activeModule = module.name;
      break;
    }
  }
};

const is_draft = ref(false);
const getDraftInfo = async () => {
  try {
    const res = await getDraft();
    if (res.data && JSON.stringify(res.data) != "[]") {
      if (is_draft.value) {
        return;
      }
      is_draft.value = true;
      ElMessageBox.confirm("检测到您有未保存的商品数据，是否重新编辑？", "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "清除缓存信息",
        type: "warning",
      })
        .then(() => {
          form.value = matchData(res.data);
          form.value.dev_status = 0;
          delete form.value.id;
          activeName.value = form.value.goods_sku[0]?.sku;
        })
        .catch(async (action) => {
          if (action === "cancel") {
            await delDraft();
          }
        })
        .finally(() => {
          is_draft.value = false;
        });
    }
  } catch (e) {
    throw Error(e);
  }
};

// 保存草稿
const saveDraftInfo = async () => {
  const newForm = deepClone(form.value);
  newForm.goods_sku = newForm.goods_sku.map((item) => {
    item.goods_sku_description = item.goods_sku_description.filter((j) => {
      if (j.show != false) {
        return j;
      }
    });

    item.goods_sku_title =
      item.goods_sku_title &&
      item.goods_sku_title.filter((i) => {
        if (i.show && i.language_id) {
          return i;
        }
      });
    item.goods_sku_gallery = item.goods_sku_gallery.map((i) => {
      i.contents = i.contents.filter((j) => j.values.length > 0);
      return i;
    });
    item.goods_sku_remark.edit_remark =
      item.goods_sku_remark.edit_remark == "<p><br></p>"
        ? ""
        : item.goods_sku_remark.edit_remark;
    item.goods_sku_remark.inspection_remark =
      item.goods_sku_remark.inspection_remark == "<p><br></p>"
        ? ""
        : item.goods_sku_remark.inspection_remark;
    item.goods_sku_head_freight = item.goods_sku_head_freight
      .filter((j) => {
        if (j.id || j.single_freight || j.single_tax_fee) {
          return j;
        }
      })
      .map((k) => {
        return {
          id: k.id,
          base_head_freight_id: k.base_head_freight_id,
          single_freight: k.single_freight || 0,
          single_tax_fee: k.single_tax_fee || 0,
        };
      });
    return item;
  });

  newForm.goods_spu_specification = newForm.goods_spu_specification
    .filter((j) => {
      if (j.show != false) {
        return j;
      }
    })
    .map((i) => {
      i.values = i.values.filter((i) => {
        if (i.show && i.language_id) {
          return i;
        }
      });
      return i;
    });

  try {
    await saveDraft(newForm);
  } catch (e) {
    throw Error(e);
  }
};

let timer = null;
onMounted(async () => {
  if (!commonStore.logisticsOptions) {
    commonStore.getLogisticsList();
  }
  await fetchOption();
  if (!commonStore.countryOptions) {
    commonStore.getCountryList();
  }
  // await initPage();
  await getBaseHeadFreightList();
  await getExchangeRate();
  // window.addEventListener("resize", handleResize);
});

const initPage = async () => {
  handleType.value = route.query?.type;
  sku_id.value = route.query?.sku_id;
  sku.value = route.query?.sku;
  sku_product_type.value = route.query?.sku_product_type;
  if (route.query?.spuId || route.query?.productId) {
    spuId.value = route.query?.spuId || route.query?.productId;
    await queryDetail(route.query.type);
  }
  if (route.query.type == "add") {
    initForm();
    form.value.developer_id = window.userInfo.user.user_id || "";
    initSpecification();
    getDraftInfo();
    if (sku_product_type.value == 2) {
      nextTick(async () => {
        form.value.spu_category = [271];
        await spuInfoRef.value.changeCategory();
      });
    }
  }
  // FlowRef.value.init();
  if (route.query.type == "add" || route.query.type == "createSKU") {
    timer = setInterval(saveDraftInfo, 60000); // 设置每分钟触发一次请求
  } else {
    clearInterval(timer); // 清除定时器
  }
};

const initForm = () => {
  form.value = {
    spu: "",
    spu_category: [],
    is_notify: false,
    imitation_remark: "",
    is_notify: false,
    need_photo: 1,
    need_processing: 2,
    recommended_level: "",
    authentication: [],
    spu_cn_title: "",
    spu_en_title: "",
    specifications: "",
    spu_status: 1,
    goods_source: 1,
    developer_id: "",
    purchaser_id: null,
    dev_reviewer_id: null,
    quality_inspector_id: null,
    img_processor_id: null,
    editor_id: null,
    goods_sku: [],
    spu_unit: null,
    brand_type: 1,
    // logistics_attributes: null,
    // logistics_attributes_name: '',
    goods_spu_sales_info: {
      suggested_sales_price: "",
      currency: "",
      currency_id: "",
      warehouse_id: "",
      suggested_header_channel: "",
      custom_specification: [{ name: "", value: "" }],
      competing_products_link: [""],
      spu_unit: "",
      packaging_method: "",
      plug_specification: "",
    },
    // is_push_to_saihe: 1,
    dev_status: 0,
  };
  setTimeout(() => {
    const logistics = logisticsOptions.value.find((i) => i.label == "普货");
    form.value.logistics_attributes = logistics?.value;
    form.value.logistics_attributes_name = logistics?.label;
  }, 1500);
};

const routeQuery = ref();

watch(
  router.currentRoute,
  (newRouter, oldRouter) => {
    if (newRouter.path == "/task/product/add") {
      if (JSON.stringify(newRouter.query) !== "{}") {
        if (JSON.stringify(newRouter.query) != JSON.stringify(routeQuery.value)) {
          initPage();
          routeQuery.value = newRouter.query;
        }
        if (scrollPosition.top > 0) {
          setTimeout(() => {
            scrollTo(scrollPosition.top);
          }, 100);
        }
      }
    } else {
      clearInterval(timer); // 清除定时器
    }
  },
  { immediate: true, deep: true }
);

// 跳转页面指定高度
const scrollTo = (height) => {
  const container = document.querySelector("#scrollContainer");
  container.scrollTo({
    top: height,
    behavior: "auto",
  });
};

onBeforeUnmount(() => {
  clearInterval(timer); // 清除定时器
});

// 审核通过
const handleAudit = async (flag) => {
  try {
    const res = await review({
      spuIds: spuId.value,
      reviewType: form.value.dev_status == 2 ? 1 : form.value.dev_status == 3 ? 2 : "",
      reviewOpinion: flag,
      reviewRemark: "",
    });
    if (res.data) {
      ElMessage.success(res.message);
      queryDetail("edit");
    } else {
      ElMessage.error(res.message);
    }
  } catch (e) {
    throw Error(e);
  }
};

// 检测侵权
const infringementRef = ref();
const handleInfringement = async () => {
  const {
    spu_title,
    keyword,
    detail_description,
    text_description,
    highlights_description,
    package_description,
    mobile_description,
  } = form.value.goods_spu_description.find((i) => i.language_id == 1);
  try {
    const res = await infringementDetection({
      brand_name: form.value.brand_name,
      spu_title,
      keyword,
      detail_description,
      text_description,
      highlights_description,
      package_description,
      mobile_description,
    });
    if (res.data.length) {
      infringementRef.value.open(res.data);
      return;
    }
    ElMessage.success("检测无异常");
  } catch (e) {
    throw Error(e);
  }
};

const changeTab = async (val) => {
  generalactive.value = val;
};

const copySKURef = ref();
const copySKUFun = async (type) => {
  if (form.value.goods_sku.length <= 1) {
    ElMessage.error("暂无可复制SKU信息");
    return;
  }
  // showCopySKU.value = true
  copySKURef.value.open(type, activeName.value);
};

const confirmCopy = async () => {
  if (!copySKU.value) {
    ElMessage.error("请选择需要复制的SKU");
    return;
  }
  if (copySKU.value == activeName.value) {
    ElMessage.error("不能复制当前SKU, 请检查重试");
    return;
  }

  const activeNameIndex = form.value.goods_sku.findIndex(
    (item) => item.custom_sku == activeName.value
  );
  const copyIndex = form.value.goods_sku.findIndex(
    (item) => item.custom_sku == copySKU.value
  );
  const goods_sku = deepClone(form.value.goods_sku);
  const copyData = deepCopyWithPreserveId(
    goods_sku[copyIndex],
    goods_sku[activeNameIndex],
    goods_sku[activeNameIndex].sku
  );
  form.value.goods_sku[activeNameIndex] = copyData;
  showCopySKU.value = false;
};

const deepCopyWithPreserveId = (source, target, sku) => {
  for (const key in source) {
    if (source.hasOwnProperty(key)) {
      if (typeof source[key] === "object" && source[key] !== null) {
        // 如果属性值是对象且不为 null，递归调用 deepCopyWithPreserveId
        target[key] = deepCopyWithPreserveId(source[key], target[key] || {}, sku);
      } else if (
        key === "id" ||
        key === "sku_id" ||
        key === "custom_sku" ||
        key === "suffixSKU" ||
        key === "prefixSKU" ||
        key === "sku_cn_title" ||
        key === "sku_en_title" ||
        key === "sku_code" ||
        key === "main_attribute" ||
        key === "specifications" ||
        key === "title" ||
        key == "color" ||
        (key === "size" && target.hasOwnProperty(key))
      ) {
        // 保留第二个对象内嵌套结构的 id 属性不变
        continue;
      } else {
        // 复制其他属性值
        target[key] = source[key];
        target["sku"] = sku;
      }
    }
  }
  return target;
};

const removeIds = (obj) => {
  const item = obj;
  delete item.id;
  delete item.sku_id;
  delete item.spu_id;
  return item;
};
const removeArrayIds = (list, sku) => {
  list &&
    list.forEach((item) => {
      if (item.sku) {
        item.sku = sku;
      }
      delete item.id;
      delete item.sku_id;
      delete item.spu_id;
    });
  return list;
};

const removeArraysIds = (list, sku) => {
  list.forEach((i) => {
    delete i.id;
    delete i.sku_id;
    delete i.spu_id;

    i.contents.forEach((j) => {
      j.values.forEach((k) => {
        if (k.sku) {
          k.sku = sku;
        }
        delete k.id;
        delete k.sku_id;
        delete k.spu_id;
      });
    });
  });
  return list;
};

// const containerSKu = ref();
// const hasOverflow = ref(false);
// const showSku = ref([]);
// const hideSku = ref([]);

const goods_sku_list = computed(() => form.value.goods_sku);
// watch(
//   goods_sku_list,
//   (val) => {
//     if (val) {
//       nextTick(() => {
//         handleResize();
//       });
//     }
//   },
//   { deep: true }
// );

// const handleResize = () => {
//   let ind = Math.floor((containerSKu.value?.clientWidth - 120) / 260);
//   hasOverflow.value = ind < goods_sku_list.value?.length;
//   showSku.value = goods_sku_list.value?.slice(0, ind);
//   hideSku.value = goods_sku_list.value?.slice(ind);
// };

const skuLoading = ref(false);
const handleTag = (val) => {
  skuLoading.value = true;
  // activeName.value = val;
  setTimeout(() => {
    skuLoading.value = false;
  }, 1000);
};

// 处理多属性为空的情况
const creatSpecification = (sku_specification) => {
  const { attributes, header } = sku_specification;
  const specification_list = header.map((i, k) => {
    i.is_relation_img = 0;
    i.group_name = i.name;
    i.loading = false;
    i.show = true;
    i.valueName = "";
    i.values = [
      {
        language_name: "中文",
        language_id: 1,
        language_code: "zh-chs",
        show: true,
        name: i.name,
        language_values: [
          {
            language_id: 1,
            group: k + 1,
            spu_id: form.value.spu,
            name: i.name,
            value: attributes[i.key],
          },
        ],
      },
      {
        language_name: "英语",
        language_code: "en",
        language_id: 2,
        show: true,
        name: "color",
        language_values: [
          {
            language_id: 2,
            group: k + 1,
            spu_id: form.value?.spu || "",
            name: i.name,
            value: attributes[i.key],
          },
        ],
      },
    ];
    return i;
  });
  return specification_list;
};

// 获取头程费用设置
const base_head_freight_list = ref([]);
const getBaseHeadFreightList = async () => {
  try {
    const res = await queryBaseHeadFreightList({
      pageSize: 100,
    });

    base_head_freight_list.value = res.data.map((item) => {
      const newId = item.id;
      item.base_head_freight_id = newId;
      delete item.id;
      return item;
    });
  } catch (e) {
    throw Error(e);
  }
};

provide("base_head_freight_list", base_head_freight_list);

const exchange_rate = ref("");
const getExchangeRate = async () => {
  try {
    const res = await getCurrency({
      currency: "USD",
    });
    exchange_rate.value = res.data[0]?.exchange_rate;
  } catch (e) {
    throw Error(e);
  }
};

// 检测SKU辅料
const checkSKUAccessories = async (sku_ids) => {
  if (sku_ids?.length == 0) {
    return false;
  }
  try {
    const res = await getSKUDetails({
      id: sku_ids,
    });
    for (let i = 0; i < res.data.length; i++) {
      const { length, width, height } = res.data[i]?.packing_size_cm;
      const dimensions = [length, width, height].sort((a, b) => a - b);
      if (dimensions[0] > 0 && dimensions[1] >= 10 && dimensions[2] >= 15) {
        return true;
      }
    }
    return false;
  } catch (error) {
    console.error("Error fetching SKU details:", error); // 处理可能的错误
    return false;
  }
};

// 同步SPU 名称到SKU
const syncName = async () => {
  multiAttributeRef.value.inputFocus();
};

const settingWeight = () => {
  const defaultPackingWeight = ""; // 设定一个合理的默认值
  // 检查 spu_category 是否存在且不为空
  if (!form.value.spu_category || form.value.spu_category.length < 1) {
    add_sku_info.value.add_weight = defaultPackingWeight;
  } else {
    const category = form.value.spu_category[0];
    // 使用对象映射来简化逻辑
    const weightMapping = {
      ...classified_first.reduce((acc, val) => ({ ...acc, [val]: 30 }), {}),
      ...classified_second.reduce((acc, val) => ({ ...acc, [val]: 15 }), {}),
      ...classified_third.reduce((acc, val) => ({ ...acc, [val]: 50 }), {}),
    };
    add_sku_info.value.add_weight = weightMapping[category] || defaultPackingWeight;
  }
};

const current_sku = computed(() => {
  return form.value.goods_sku.find((item) => item.sku === activeName.value);
});

const current_index = computed(() => {
  return form.value.goods_sku.findIndex((item) => item.sku === activeName.value);
});

const changeGeneralactive = () => {
  if (generalactive.value == "9") {
    generalactive.value = "Supplier";
  }
};
</script>

<style lang="scss" scoped>
@import "../index.scss";
</style>
